<template>
  <div>
    <Form :label-width='130' :ref='formData' :model='formData' class="form" :rules="formrules">
      <FormItem label="类型：">
            <RadioGroup v-model="formData.linkUrl">
              <Radio :label="0">快商通</Radio>
              <Radio :label="1">电话</Radio>
              <Radio :label="2">无链接</Radio>
            </RadioGroup>
      </FormItem>
      <FormItem label="上传类别：" prop="tagIds" class="typeName">
        <Row>
          <Col span="8">
            <Select v-model="formData.tagIds" style="width:200px" placeholder="请选择上传类别" filterable >
                <Option v-for="item in typeList" :value="item.id" :key="item.id">{{ item.name }}</Option>
            </Select>
          </Col>
          <Col span="12" ><Button type="primary" @click="changetype">添加类别</Button></Col>
        </Row>
      </FormItem>
      <div class="upbox"><Button type="primary" size="large" @click="saveUpload(formData)" :loading="saveLoading">开始上传</Button></div>
      <Divider dashed />
      <div>
        <div class="demo-upload-list" v-for="(item,index) in uploadList" :key="index">
            <template v-if='item.imgurl'>
                <img :src="item.imgurl" width="100%" height="350px">
                <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(item)"></Icon>
                    <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                </div>
            </template>
            <template v-else>
                <Progress v-if="showProgress" :percent="percentage" hide-info></Progress>
            </template>
        </div>
        <Upload
            ref='upload'
            multiple
            :format="['jpg','png','gif','jpeg','webp']"
            :action="requestAction"
            :headers="{'Authorization': 'Bearer ' + token,'projectid':project}"
            :before-upload="beforeUpLoad"
            :on-progress="onprogress"
            :on-success="(res) => upSuccess(res)"
            :on-remove="(res)=>upRemove(res)"
            :on-error="upError"
            :show-upload-list="false"
            type="drag"
            >
            <div style="padding: 20px 0">
                <Icon type="ios-cloud-upload" size="52" style="color: #3399ff"></Icon>
                <p>点击或拖动上传图片，支持多图上传</p>
            </div>
        </Upload>
    </div>
    </Form>
    <!-- 添加类别-->
     <Modal v-model="modalstatus" title="添加图库类别" width="500">
       <Form :ref='modalForm' :model='modalForm' :rules="rules">
          <FormItem >
            <Input v-model="modalForm.tags_name"  placeholder="请添加类别" maxlength="10" />
          </FormItem>
       </Form>
      <div slot='footer' class="footer">
          <!-- <Button @click='canceledit(modalForm)'>取消</Button> -->
          <Button  type='primary' :loading="subloading" @click='submitedit(modalForm)'>保存</Button>
     </div>
    </Modal>
    <Modal title="图片" v-model="imgVisible">
        <img :src="viewingImg" v-if="imgVisible" style="width: 100%">
    </Modal>
  </div>
</template>
<script>
    import { materialtype, catesAdd, saveImgupload } from '@/api/myuplod.js'
    import Setting from '@/setting';
    import util from '@/libs/util';
    export default {
        data () {
            return {
                project: util.storage.get('currentProject'),
                token: util.cookies.get('token'),
                baseUrl: Setting.apiBaseURL,
                url: '',
                formData: {
                    linkUrl: 0,
                    tagIds: ''
                },
                formrules: {
                    tagIds: [{ required: false, message: '请选择类别', trigger: 'change' }]
                },
                requestAction: '',
                requestHeaders: {},
                typeList: [],
                file: null,
                loadingStatus: false,
                imgList: [],
                uploadList: [], // 缩略图
                // imgurl: '@/assets/images/logo-small.png',
                modalForm: {
                    tags_name: ''
                },
                rules: {
                    tags_name: [{ required: true, message: '请添加类别', trigger: 'blur' }]
                },
                modalstatus: false,
                subloading: false,
                saveLoading: false,
                imgVisible: false,
                percentage: 0,
                showProgress: false
            }
        },
        created () {
            this._gettype()
        },
        mounted () {
            this.requestAction = this.baseUrl + `/v1/material/upload/imgs-upload`;
            this.url = this.baseUrl + `/library_image_tmp/`
            // this.uploadList = this.$refs.upload.fileList;
        },
        methods: {
            // 获取类别
            _gettype () {
                materialtype({}).then(res => {
                    this.typeList = res;
                }).catch(() => {
                    // this.tableLoading = false
                })
            },
            // 添加类别
            changetype () {
                this.modalForm.tags_name = ''
                this.modalstatus = true
            },
            // 类别确定
            submitedit (modalForm) {
                this.$refs[modalForm].validate((valid) => {
                    if (valid) {
                        this.subloading = true;
                        catesAdd({ tags_name: this.modalForm.tags_name }).then(res => {
                            this.$Message.success('添加成功');
                            this.modalstatus = false;
                            this.subloading = false;
                            this._gettype()
                        }).catch(() => {
                            this.modalstatus = false;
                            this.subloading = false;
                        })
                    } else {
                        // this.$Message.error('请完善表格。');
                    }
                })
            },
            handleView (item) {
                // console.log(item);
                this.viewingImg = item.imgurl;
                this.imgVisible = true;
            },
            handleRemove (item) {
                this.$Modal.confirm({
                    title: '提示',
                    content: '确定删除文件?',
                    onOk: () => {
                        this.uploadList.splice(this.uploadList.indexOf(item), 1);
                        this.imgList.splice(this.uploadList.indexOf(item), 1)
                    }
                });
            },
            // 提交数据
            saveUpload (formData) {
                if (this.formData.tagIds) {
                    this.saveLoading = true;
                    let params = {
                        linkUrl: this.formData.linkUrl === 0 ? '/swt/' : this.formData.linkUrl === 1 ? '/tell/' : this.formData.linkUrl === 2 ? 'javascript:;' : '',
                        tagIds: this.formData.tagIds,
                        imgList: this.imgList.join(';')
                    }
                    saveImgupload(params).then(res => {
                        this.$Message.success('上传成功');
                        this.saveLoading = false
                        this.formData.linkUrl = 0
                        this.formData.tagIds = ''
                        this.imgList = []
                        this.uploadList = []
                    }).catch(() => {
                        this.saveLoading = false;
                    })
                } else {
                    this.$Message.error('请选择上传类别');
                }
                // this.$refs[formData].validate((valid) => {

                // })
            },
            // handleUpload (file) {
            //     this.file = file;
            //     return false;
            // },
            // upload () {
            //     this.loadingStatus = true;
            //     setTimeout(() => {
            //         this.file = null;
            //         this.loadingStatus = false;
            //         this.$Message.success('Success')
            //     }, 1500);
            // },
            upRemove (res) {
                // console.log(res, 'splice')
                // this.imgList.splice
            },
            // 上传成功前
            beforeUpLoad () {
                //
            },
            // 上传中
            onprogress (event, file, fileList) {
                this.percentage = Math.round(event.loaded * 100 / event.total);
            },
            // 上传成功后
            upSuccess (response) {
                // debugger
                // console.log(file)
                let url = response.data.map(item => item.img_url)
                this.imgList.push(url)
                let imgurl = `${this.baseUrl}/library_image_tmp${url}`

                this.uploadList.push({ imgurl: imgurl })
                this.percentage = 0;
            },
            // 上传失败
            upError (event, file, fileList) {
                //
            }

        }
    }
</script>
<style scoped>
.form{
  position: relative;
}
.upbox /deep/.ivu-btn-primary{
  position: absolute;
  right: 40px;
  top:20px
}
 .demo-upload-list{
        display: inline-block;
        width: 60px;
        height: 60px;
        text-align: center;
        line-height: 60px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0,0,0,.2);
        margin-right: 4px;
    }
    .demo-upload-list img{
        width: 100%;
        height: 100%;
    }
    .demo-upload-list-cover{
        display: none;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        background: rgba(0,0,0,.6);
    }
    .demo-upload-list:hover .demo-upload-list-cover{
        display: block;
    }
    .demo-upload-list-cover i{
        color: #fff;
        font-size: 20px;
        cursor: pointer;
        margin: 0 2px;
    }
.typeName::before{
    content: '*';
    color:#f00;
    font-size: 16px;
    position: absolute;
    /* top: 25%; */
    left:42px;
}
</style>
